<?php
/**
 * Created by PhpStorm.
 * User: 554665488
 * Date: 2018-7-9
 * Time: 17:13
 * @description:
 * @Author: yfl
 * @QQ 554665488
 */

namespace App\Api\Auth;


use App\Http\Controllers\Controller;
use App\User;
use Dingo\Api\Exception\StoreResourceFailedException;
use Dingo\Api\Routing\Helpers;
use Illuminate\Foundation\Auth\RedirectsUsers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;
use Tymon\JWTAuth\Facades\JWTAuth;
/**
 * # Group DemoController
 *
 * @Resource("", uri="/api")
 */
class RegisterController extends Controller
{
    use RedirectsUsers;
    use Helpers;

    /**
     * 根据用户ID获取用户
     *
     * [需授权] 返回单个用户
     *
     * @Get("/api/user/ID")
     * @Parameters({
     *      @Parameter("id", type="integer", required=true, description="用户ID")
     * })
     * @Request(headers={"Authorization": "Bearer token"})
     * @Response(200, body={})
     */
    public function test($id)
    {
         return [];
    }

    public function register(Request $request)
    {
//        return;
        $validator = $this->validator($request->all());
        if ($validator->fails()) {
            throw new StoreResourceFailedException("validation Error" . $validator->errors());
        }
        $user = $this->create($request->all());

        if ($user->save()) {

            $token = JWTAuth::fromUser($user);

            return $this->response->array([
                "token" => $token,
                "message" => "User created",
                "status_code" => 201
            ]);
//eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJodHRwOlwvXC8xMjcuMC4wLjE6ODA4M1wvYXBpXC9yZWdpc3RlciIsImlhdCI6MTUzMTEyOTQ2OSwiZXhwIjoxNTMyMzM5MDY5LCJuYmYiOjE1MzExMjk0NjksImp0aSI6InIwdWxxTml5MVd0bjZ6YXIiLCJzdWIiOjQsInBydiI6Ijg3ZTBhZjFlZjlmZDE1ODEyZmRlYzk3MTUzYTE0ZTBiMDQ3NTQ2YWEifQ.soqVir7hFmYVhURAoyPBs_3Lb1DR0RGwnuAIHQ71hCQ
        } else {
            return $this->response->error("User Not Found...", 404);
        }
    }

    protected function validator(array $data)
    {
        return Validator::make($data, [
            'name' => 'required|unique:users',
            'email' => 'required|email|max:255|unique:users',
            'password' => 'required|min:6',
        ]);
    }

    protected function create(array $data)
    {
        return User::create([
            'name' => $data['name'],
            'email' => $data['email'],
            'password' => bcrypt($data['password']),
        ]);
    }
}